package controllers;

import entity.User;
import view.ChatInterface;
import view.RegisterInterface;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.stage.Stage;
import jdbc.Function;

/**
 * @author zjw
 * @date 2020/1/7 14:38
 */
public class LoginInterfaceControllers {
    private Hyperlink registerHyperlink;
    private Button loginButton;
    private Stage primaryStage;
    private TextField textField;
    private PasswordField passwordField;
    public LoginInterfaceControllers(Stage primaryStage, TextField textField, PasswordField passwordField) {
        this.primaryStage = primaryStage;
        this.loginButton = new Button();
        this.registerHyperlink = new Hyperlink();
        this.textField = textField;
        this.passwordField = passwordField;
    }

    /**
     * 获得一个登陆按钮
     * @return 返回一个带有登录监听器的按钮
     */
    public Button getLoginButton() {
        loginButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                User user = new User(textField.getText(), passwordField.getText());
                Function function = new Function();
                int flag = function.login(user);
                if(flag == 1){
                    // 将此时输入框中的id暂存
                    String id = user.getId();
                    // 将数据库中的存在的该id的User给user
                    user = function.findUser(id);

                    Platform.setImplicitExit(false);
                    primaryStage.close();   // 关闭当前的登录界面
                    User finalUser = user;
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            new ChatInterface(finalUser, primaryStage).start();
                        }
                    });

                } else {
                    Alert errorAlert = new Alert(Alert.AlertType.ERROR);
                    errorAlert.setTitle("ERROR");
                    errorAlert.setHeaderText("号码或密码输入有误!");
                    errorAlert.setContentText("号码或密码输入有误，请重新输入!");
                    errorAlert.showAndWait();
                }
            }
        });
        return loginButton;
    }

    public Hyperlink getRegisterHyperlink() {
        /**
         *  设置按钮的注册超链接的点检事件
         *  具体是获得信息并返回
         */
        registerHyperlink.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                primaryStage.close();
                try {
                    new RegisterInterface(new Stage()).start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return registerHyperlink;
    }
}
